const pathToRegExp = require('path-to-regexp')


function Layer(path, handler) {  // path 维度
    this.path = path
    this.handler = handler
    this.regexps = pathToRegExp(path, (this.keys = [])) // 等同于  this.keys = []    pathToRegExp(path,this.keys)

}

Layer.prototype.match = function (pathname) {
    let matches = pathname.match(this.regexps)
    // console.log(this.regexps) // /^\/user\/(?:([^\/]+?))\/(?:([^\/]+?))\/xxx\/?$/i
    // console.log(this.keys) // [{ name: 'id', optional: false, offset: 7 }, { name: 'name', optional: false, offset: 22 }]
    // console.log(matches) // [ '/user/147/ljp/xxx', '147',    'ljp',   index: 0,  input: '/user/147/ljp/xxx',  groups: undefined ]
    if (matches) { // 正则路由
        this.params = this.keys.reduce((obj, cur, index) => {
            obj[cur.name] = matches[index + 1]
            return obj
        }, {})
        return true
    }
    if (this.path === pathname) {
        return true
    }
    if (!this.route) { //  没有route说明是中间件
        if (this.path === '/') {
            return true
        }
        if (pathname.startsWith(this.path + '/')) {
            return true
        }
    }
    return false
}


Layer.prototype.handle_request = function (req, res, next) {
    this.handler(req, res, next)
}

module.exports = Layer